package com.dr.common.ution;

import java.util.Map;

import com.dr.common.pojo.RepMess;
import com.dr.common.pojo.WeChatContent;
import com.dr.common.pojo.WeChatFinalValue;
import com.dr.common.pojo.WeChatOpenid;


/**
 * 微信操作工具类
 * @author tugou
 *
 */
public class WeChatUtil {
	
	/**
	 * 页面授权，获取微信Openid
	 * @param code
	 * @return
	 */
	public static WeChatOpenid getWeChatOpenid(String code){
		String url = WeChatFinalValue.ACCESS_OPENID_URL;
		url = url.replaceAll("APPID", WeChatContent.getInstance().getAppId());
		url = url.replaceAll("SECRET", WeChatContent.getInstance().getAppSecurt());
		url = url.replaceAll("CODE", code);
		String result = HttpClientUtil.doGet(url);
		Boolean isSuccess = checkRequestSucc(result);
		WeChatOpenid content;
		if(isSuccess){
			
			content = JsonUtil.toObject(result, WeChatOpenid.class);
		}else
		{
			RepMess mess = JsonUtil.toObject(result, RepMess.class);
			content = new WeChatOpenid();
			content.setMess(mess);
		}
		return content;
	}
	
	/**
	 * 检查请求是否成功
	 * @param content
	 * @return
	 */
	public static Boolean checkRequestSucc(String content) {
		Map<String, Object> map = JsonUtil.toObject(content, Map.class);
		if(!map.containsKey("errcode"))
			return true;		
		Double errcode = (Double) map.get("errcode");
		if(errcode == 0)
			return true;
		return false;
	}
	
	/**
	 * 获取请求返回值
	 * @param content
	 * @return
	 */
	public static Integer getRequestCode(String content){
		Map<String, String> map = JsonUtil.toObject(content, Map.class);
		if(map.containsKey("errcode"))
			return Integer.valueOf(map.get("errcode"));
		return -1;
	}
	
	/**
	 * 获取请求返回消息
	 * @param content
	 * @return
	 */
	public static String getRequestMsg(String content) {
		Map<String, String> map =JsonUtil.toObject(content, Map.class);
		if(map.containsKey("errcode"))
			return map.get("errmsg").toString();
		return null;
	}
}
